$(() => {
  if (/http[s]:\/\/v1\.mikecrm.com\/form\.php\#\/submit\?id=.+/.test(location.href)) {
    let runBtn = `
      <button class="yhby_gather" id="yhby_gather">生成表单</button>
    `
    $('.fbl_listDetails').append(runBtn)
    
    $('#yhby_gather').click(() => {
      chrome.runtime.sendMessage({ 'cmd': 'getTemplate', 'url': '/templates/mikecrm-form.html' },function(tempData) {
        layer.open({
          type: 1,
          title: '关键词表单',
          area: ['600px', '600px'],
          shadeClose: false,
          shade: 0,
          content: tempData,
          success:function(layero, index) {
            renderHtml(index)
          }
        })
      })
    })
  }
})

function renderHtml(layerIndex) {
  new Vue({
    el: '#YHBY-form',
    data: {
      dataList: [
        { name: '', pcLoc: '', loc: '', shopName: '' },
        { name: '', pcLoc: '', loc: '', shopName: '' }
      ],
      company: ''
    },
    mounted() {
      this.company = $('.fbl_dFeedback li.company .fbl_dfValue').text()
    },
    methods: {
      addData() {
        if (this.dataList.length < 10) {
          this.dataList.push({ name: '', pcLoc: '', loc: '', shopName: '' })
        } else {
          layer.msg('最多可添加10个关键词')
        }
      },
      deleteData(index) {
        this.dataList.splice(index, 1)
      },
      submitData() {
        let result = this.checkForm()
        if (result.status) {
          let data = this.dataList.map(v => {
            return {...v, shopName: this.company}
          })
          chrome.extension.sendMessage({ 'cmd': 'mikecrm-to-detail', 'data': data })
          layer.close(layerIndex)
        } else {
          layer.msg(result.msg)
        }
      },
      checkForm() {
        let status = true, msg
        this.dataList.forEach(element => {
          if (!element.name) {
            status = false
            msg = '请填写关键词'
          }
          if (!/^(http|https):\/\/www\.youboy\.com\/.+/.test(element.pcLoc.trim())) {
            status = false
            msg = '推广地址不正确'
          }
          element.name = element.name.trim()
          element.pcLoc = element.pcLoc.trim()
          if (element.pcLoc.indexOf('/product/') !== -1) {
            element.loc = element.pcLoc.replace('http://www.youboy.com/mall/product/', 'https://gyp.youboy.com/h5/product/detail?id=')
          } else {
            element.loc = element.pcLoc.replace('http://www.youboy.com/s', 'https://m.youboy.com/p')
          }
        })
        return { status: status, msg: msg }
      }
    }
  })
}